package com.atguigu.interceptors;

import com.atguigu.utils.JwtHelper;
import com.atguigu.utils.Result;
import com.atguigu.utils.ResultCodeEnum;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * ClassName: $ {NAME}
 * Package: ${PACKAGE_.NAME}
 * Description:
 *           登录包含拦截器，检查请求偷是否包含有效token
 *
 *          有，有效 ，放行
 *          没有 无效 返回504
 * @Author洛小羽
 * @Create 2024/1/8 12:55
 * aVersion 1.0
 */
@Component
public class LoginProtectedInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtHelper jwtHelper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //从请求头中获取token
        String token = request.getHeader("token");

        //检查是否有效
        boolean expiration = jwtHelper.isExpiration(token);//expiration代表是否过期
        //有效放行
        if (!expiration) {
            //放行没有过期
            return true;
        }
        //无效返回504的状态json  没有json自己造个json
        Result result = Result.build(null, ResultCodeEnum.NOTLOGIN);

        //jackson提供的json字符串转换为java对象 java对象转换为json字符串
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(result);//java对象转换为json字符串
        response.getWriter().println(json);

        return false;
    }
}
